package com.lianliankan.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.lianliankan.llkan.RankActivity;
import com.lianliankan.model.Users;

public class UserAsyncTask extends AsyncTask<Object, Object, String> {
	private Users user;
	private String action;
	private Context context;

	public UserAsyncTask(Users user, String action, Context context) {
		this.user = user;
		this.action = action;
		this.context = context;
	}

	// 异步操作时执行
	@Override
	protected String doInBackground(Object... params) {
		String state = "";
		HttpHelper httpHelper = new HttpHelper();
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		NameValuePair nameValuePair1 = new BasicNameValuePair("account",
				user.getAccount());
		NameValuePair nameValuePair2 = new BasicNameValuePair("password",
				user.getPasswrod());
		if (action.equals("login")) {
			nameValuePairs.add(nameValuePair1);
			nameValuePairs.add(nameValuePair2);
			state = httpHelper.httpGetRank(nameValuePairs, "login.aspx");
		} else if (action.equals("register")) {
			NameValuePair nameValuePair3 = new BasicNameValuePair("nickname",
					user.getNickName());
			nameValuePairs.add(nameValuePair1);
			nameValuePairs.add(nameValuePair2);
			nameValuePairs.add(nameValuePair3);
			state = httpHelper.httpGetRank(nameValuePairs, "register.aspx");
		}
		return state;
	}

	// 在doInBackground后执行
	@Override
	protected void onPostExecute(String state) {
		if (state.equals("login already") || state.equals("login successfully")
				|| state.equals("register successfully")) {
			GlobalValue.account = user.getAccount();
			Intent intent = new Intent(context, RankActivity.class);
			context.startActivity(intent);
			((Activity) context).finish();
		} else if (state.equals("wrong password")
				|| state.equals("wrong account")
				|| state.equals("register unsuccessfully")) {
			AlertDialog.Builder alert = new AlertDialog.Builder(context);
			alert.setTitle(state);
			alert.show();
		}
		cancel(true);
	}
}